package org.spal.admin

import grails.converters.JSON

import org.apache.commons.lang.math.NumberUtils
import org.spal.Local;
import org.spal.Locatario;
import org.spal.Pedido;
import org.spal.Producto;
import org.spal.UsuarioRol
import org.spal.Rol
import org.springframework.dao.DataIntegrityViolationException

class LocalController {

	static allowedMethods = [save: "POST", delete: "POST"]

	def index() {
		render (view: "/admin/local/list")
	}

	def list() {
		def page = params.page as Integer
		def rows = params.rows as Integer

		if (page && rows) {
			params.max = Math.min(rows ?: 10, 100)
			params.offset = (page-1) * rows
		}

		//TODO: Create filter with "params.field" and "params.value"

		def list = Local.list(params)
		def count = Local.count()

		render([total: count, rows: list] as JSON)
	}

	def show(Long id) {
		def localInstance = Local.get(id)
		if (!localInstance) {
			render([success: false, error: message(code: 'default.not.found.message', args: [
					message(code: 'local.label', default: 'Local'),
					id
				])] as JSON)
			return
		}
		render localInstance as JSON
	}

	def save() {
		def local = (params.id) ? Local.get(params.id) : new Local()
		def locatario

		if (!local) {
			def error = [message: message(code: 'default.not.found.message', args: [
					message(code: 'local.label', default: 'Local'),
					params.id
				])]
			render([success: false, messages: [errors:[error]] ] as JSON)
			return
		} else
			locatario = (params.id) ? local.locatario : new Locatario(enabled:true,local:local)

		def version = NumberUtils.toLong(params.version)
		if (version != null) {
			if (local.version > version) {
				local.errors.rejectValue("version", "default.optimistic.locking.failure",
						[
							message(code: 'local.label', default: 'Local')] as Object[],
						"Another user has updated this Local while you were editing")
				render([success: false, messages: local.errors] as JSON)
				return
			}
		}

		local.nombre = params.nombre
		local.descripcion = params.descripcion
		if(params.habilitado)
			local.habilitado = true
		else
			local.habilitado =false
		local.fechaRegistro = new Date()
		
		def im = params.img
		if(!im.empty)
			local.foto = request.getFile('img').inputStream.bytes

		locatario.username = params.username
		locatario.password = params.password
		locatario.email = params.email
		locatario.nombre = params.locatario_nombre
		locatario.apellidos = params.locatario_apellidos
		locatario.direccion = params.locatario_direccion
		local.locatario = locatario

		if (!locatario.save(flush: true)) {
			render([success: false, messages: locatario.errors] as JSON)
			return
		}
		if(!params.id)
			UsuarioRol.create locatario,Rol.findByAuthority('ROLE_LOCATARIO')
		render([success: true] as JSON)
	}

	def delete(Long id) {
		def localInstance = Local.get(id)
		if (!localInstance)
			render([success: false] as JSON)
		else {
			try {
				Collection<UsuarioRol> userRoles = UsuarioRol.findAllByUsuario(localInstance.locatario);
				userRoles*.delete();
				localInstance.locatario.delete();
				localInstance.delete(flush: true)
				render([success: true] as JSON)
			}catch (DataIntegrityViolationException e) {
				render([success: false, erro: e.message] as JSON)
			}
		}
	}
}
